package com.doge.walknovel.utils

import java.io.*
import java.nio.charset.StandardCharsets

object FileUtils {
    fun cacheDir(child: String): File {
        return File(
            appContext.cacheDir, child
        ).also { if (!it.exists()) it.mkdirs() }
    }

    fun filesDir(child: String): File {
        return File(
            appContext.filesDir, child
        ).also { if (!it.exists()) it.mkdirs() }
    }

    fun copy(inputStream: InputStream?, outputStream: OutputStream?) {
        if (inputStream == null) return
        if (outputStream == null) return
        try {
            var read: Int
            val bytes = ByteArray(1024)
            while (inputStream.read(bytes).also { read = it } != -1) {
                outputStream.write(bytes, 0, read)
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        } finally {
            closeQuietly(inputStream)
            closeQuietly(outputStream)
        }
    }

    fun read(file: File): String? {
        if (!file.exists()) return null
        var stream: FileInputStream? = null
        var inputStream: InputStreamReader? = null
        var reader: BufferedReader? = null
        try {
            stream = FileInputStream(file)
            inputStream = InputStreamReader(stream, StandardCharsets.UTF_8)
            reader = BufferedReader(inputStream)
            var line: String?
            val result = StringBuffer()
            while (reader.readLine().also { line = it } != null) {
                result.append(line)
            }
            return result.toString()
        } catch (e: Throwable) {
            e.printStackTrace()
        } finally {
            closeQuietly(reader)
            closeQuietly(inputStream)
            closeQuietly(stream)
        }
        return null
    }

    fun write(file: File, data: String) {
        var stream: FileOutputStream? = null
        var outputStream: OutputStreamWriter? = null
        var writer: BufferedWriter? = null
        try {
            if (!file.exists()) file.createNewFile()
            stream = FileOutputStream(file)
            outputStream = OutputStreamWriter(stream, StandardCharsets.UTF_8)
            writer = BufferedWriter(outputStream)
            writer.append(data)
        } catch (e: Throwable) {
            e.printStackTrace()
            file.delete()
        } finally {
            closeQuietly(writer)
            closeQuietly(outputStream)
            closeQuietly(stream)
        }
    }

    fun size(byteCount: Int?) = size(byteCount?.toLong())
    private fun size(byteCount: Long?): String {
        if (byteCount == null) return ""
        if (byteCount < 0) return ""
        if (byteCount < 1024) return "${byteCount}B"
        if (byteCount < 1048576) return "${byteCount / 1024}KB"
        return "${byteCount / 1048576f}MB"
    }



}